
package com.aat.dxfy.redis.pool;

import java.util.HashSet;
import java.util.Set;

import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisSentinelPool;

public class RedisSentinelPoolHolder {
	private RedisSentinelPoolHolder() {
	}

	private static class PoolHoledr {
		// private static redis.clients.util.Pool pool;
		private static CustomPool customPool;
		static {
			boolean sentinelMode = "sentinel"
					.equalsIgnoreCase(CommonPropertiesUtil.getProperty("redis.mode", "sentinel"));
			// 可选值： sentinel 、 aliyun

			int maxIdle = Integer.parseInt(CommonPropertiesUtil.getProperty("redis.maxidle", "200")); // 最大空闲连接数
			int maxTotal = Integer.parseInt(CommonPropertiesUtil.getProperty("redis.maxtotal", "300")); // 最大连接数
			int maxWaitMillis = Integer.parseInt(CommonPropertiesUtil.getProperty("redis.maxwaitmillis", "300"));
			int timeout = Integer.parseInt(CommonPropertiesUtil.getProperty("redis.timeout", "3000"));

			if (sentinelMode) { // 哨兵模式
				String hosts = CommonPropertiesUtil.getProperty("redis.address", "127.0.0.1:26379");
				String masterName = CommonPropertiesUtil.getProperty("redis.mastername", "mymaster");
				String password = CommonPropertiesUtil.getProperty("redis.sentinepassword", null);

				Set<String> sentinels = new HashSet<String>();
				String[] host = hosts.split(",");
				for (int i = 0; i < host.length; i++) {
					sentinels.add(host[i]);
				}
				JedisPoolConfig poolConfig = new JedisPoolConfig();
				poolConfig.setMaxTotal(maxTotal);
				poolConfig.setMaxIdle(maxIdle);
				poolConfig.setMaxWaitMillis(maxWaitMillis);
				poolConfig.setTestOnBorrow(true);
				JedisSentinelPool pool = new JedisSentinelPool(masterName, sentinels, poolConfig, timeout, password);

				customPool = new CustomPool(pool);
			} else { // 阿里云模式
				String host = CommonPropertiesUtil.getProperty("redis.host", "127.0.0.1");
				int port = Integer.parseInt(CommonPropertiesUtil.getProperty("redis.port", "6379"));
				String password = CommonPropertiesUtil.getProperty("redis.password", null);

				JedisPoolConfig poolConfig = new JedisPoolConfig();
				poolConfig.setMaxTotal(maxTotal);
				poolConfig.setMaxIdle(maxIdle);
				poolConfig.setMaxWaitMillis(maxWaitMillis);
				poolConfig.setTestOnBorrow(false);
				poolConfig.setTestOnReturn(false);
				JedisPool pool = new JedisPool(poolConfig, host, port, timeout, password);
				customPool = new CustomPool(pool);
			}
		}
	}

	public static CustomPool getInstance() {
		return PoolHoledr.customPool;
	}
}
